// pages/UpdateDeliveryAddress/ProvinceCityDistrictSelection/ProvinceCityDistrictSelection.js
import {
  queryChinaCities
} from "../../../service/delivery-address"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 目前在选第N级地区
    step: 0,
    // 省
    province: null,
    provinceCode: null,
    // 市
    city: null,
    cityCode: null,
    // 区
    district: null,
    districtCode: null,
    // 省份数据
    provinces: [],
    // 市级数据
    cities: [],
    // 区/县级数据
    districts: [],
    // 事件通道
    eventChannel: null
  },
  /**
   * 点击一级区域 
   */
  onTapOneLevelRegion() {
    if (this.data.step > 0) {
      this.setData({
        step: 0
      })
    }
  },
  /**
   * 点击二级区域
   */
  onTapTwoLevelRegion() {
    if (this.data.step > 1) {
      this.setData({
        step: 1
      })
    }
  },
  /**
   * 点击三级区域
   */
  onTapThreeLevelRegion() {

  },
  /** 
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    const res = await queryChinaCities()
    this.setData({
      eventChannel: this.getOpenerEventChannel(),
      provinces: JSON.parse(res.data)
    })
  },
  /**
   * 点击选择省
   */
  onTapSelectProvince(event) {
    const code = event.currentTarget.dataset.code
    const provinceData = this.data.provinces.find(item => item.code === code)
    this.setData({
      step: 1,
      province: provinceData.province,
      provinceCode: provinceData.code,
      cities: provinceData.citys
    })
  },
  /**
   * 点击选择市
   */
  onTapSelectCity(event) {
    const code = event.currentTarget.dataset.code
    const cityData = this.data.cities.find(item => item.code === code)
    this.setData({
      step: 2,
      city: cityData.city,
      cityCode: cityData.code,
      districts: cityData.areas
    })
  },
  /**
   * 点击选择区
   */
  onTapSelectDistrict(event) {
    const code = event.currentTarget.dataset.code
    const districtData = this.data.districts.find(item => item.code === code)
    this.setData({
      district: districtData.area,
      districtCode: districtData.code
    })
    this.data.eventChannel.emit('acceptRegionData', {
      province: this.data.province,
      city: this.data.city,
      district: this.data.district
    })
    wx.navigateBack()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})